#include <iostream>
#include <signal.h>
#include <unistd.h>
#include <cassert>
#include <sys/wait.h>
#include <sys/types.h>

using namespace std;

int cnt = 1;
void PrintSig(sigset_t &pending)
{
    
    cout << cnt++ << " : pending map： ";
    for (int sigo = 31; sigo > 0; sigo--)
    {
        if (sigismember(&pending, sigo)) cout << "1";
        else cout << "0";
    }
    cout << endl;
}

void handler(int SIG)
{
    cout << SIG << "号正在被捕捉递达处理......" << endl;
    sigset_t pending;
    sigemptyset(&pending);
    int n = sigpending(&pending);
    assert(n == 0);
    PrintSig(pending);
    cout << SIG << "递达处理finished" << endl;
}
int main()
{
    signal(2,handler);
    // 1.创建阻塞
    sigset_t block, oblock;
    sigemptyset(&block);
    sigemptyset(&oblock);
    sigaddset(&block, 2);

    int n = sigprocmask(SIG_SETMASK, &block, &oblock);
    assert(n == 0);
    cout << "block success" << endl;
    cout << "process pid : " << getpid() << endl;
    int cnt = 0;

    while (true)
    {
        // 2.创建pending
        sigset_t pending;
        sigemptyset(&pending);
        n = sigpending(&pending);
        assert(n == 0);
        PrintSig(pending);
        cnt++;
        if (cnt == 20)
        {
            cout << "解除对2号信号的屏蔽" << endl;
            n = sigprocmask(SIG_UNBLOCK, &block, &oblock);
            assert(n == 0);
        }
        sleep(1);
    }

    return 0;
}